import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { queryMyCarts, addCartItem, removeCartItem, removeCartItems, updateCart } from '@/api/cart.js'
import { ElMessage } from 'element-plus'

export const useCartStore = defineStore('cart', () => {
  // 购物车数据
  const cartItems = ref([])
  const loading = ref(false)

  // 从服务器获取购物车数据
  const fetchCartItems = async () => {
    try {
      loading.value = true
      const result = await queryMyCarts()
      cartItems.value = result || []
      // 给每个商品添加选中状态
      cartItems.value.forEach(item => {
        item.selected = true
      })
    } catch (error) {
      ElMessage.error('获取购物车数据失败')
      cartItems.value = []
    } finally {
      loading.value = false
    }
  }

  // 添加商品到购物车
  const addToCart = async (product) => {
    try {
      // 生成规格索引数组
      let specsIndex = null
      if (product.selectedSpecs && Object.keys(product.selectedSpecs).length > 0) {
        const specsIndexArray = []
        if (product.specs) {
          Object.keys(product.specs).forEach(specName => {
            const specOptions = product.specs[specName]
            const selectedValue = product.selectedSpecs[specName]
            if (Array.isArray(specOptions) && selectedValue) {
              const index = specOptions.indexOf(selectedValue)
              specsIndexArray.push(index >= 0 ? index : 0)
            } else {
              specsIndexArray.push(0)
            }
          })
        }
        specsIndex = JSON.stringify(specsIndexArray)
      }

      // 将选中的规格值转换为Map<String, List<String>>格式
      const specsMap = {}
      if (product.selectedSpecs && Object.keys(product.selectedSpecs).length > 0) {
        Object.keys(product.selectedSpecs).forEach(key => {
          const selectedValue = product.selectedSpecs[key]
          if (selectedValue) {
            specsMap[key] = [selectedValue]
          }
        })
      }

      const cartData = {
        productId: product.id,
        quantity: product.quantity || 1,
        productPrice: product.originalPrice || product.price,
        productCurrentPrice: product.price,
        productTitle: product.name, 
        productImage: product.image, 
        specs: specsMap,
        specsIndex: specsIndex
      }

      // 调用后端API添加商品到购物车
      const result = await addCartItem(cartData)
      
      // 检查返回结果
      if (result && result.data) {
        if (typeof result.data === 'object' && result.data !== null && !Array.isArray(result.data)) {
          const newCartItem = result.data
          newCartItem.selected = true
          
          const existingItemIndex = cartItems.value.findIndex(item => 
            item.productId === newCartItem.productId && 
            item.specsIndex === newCartItem.specsIndex
          )
          
          if (existingItemIndex !== -1) {
            cartItems.value[existingItemIndex].quantity = newCartItem.quantity
          } else {
            cartItems.value.push(newCartItem)
          }
        } else {
          await fetchCartItems()
        }
        
        ElMessage.success('商品已成功加入购物车！')
      } else {
        await fetchCartItems()
        ElMessage.success('商品已成功加入购物车！')
      }
    } catch (error) {
      console.error('添加商品到购物车失败:', error)
      ElMessage.error('添加商品到购物车失败')
    }
  }

  // 更新商品数量到服务器
  const updateQuantityToServer = async (cartItemId, quantity) => {
    const item = cartItems.value.find(item => item.id === cartItemId)
    if (!item) {
      throw new Error('商品不存在')
    }

    try {
      await updateCart({
        id: cartItemId,
        quantity: quantity
      })
      item.quantity = quantity
    } catch (error) {
      throw error
    }
  }

  // 更新购物车商品规格
  const updateCartItemSpecs = async (updateData) => {
    const item = cartItems.value.find(item => item.id === updateData.id)
    if (!item) {
      throw new Error('商品不存在')
    }

    try {
  
      const cartUpdateData = {
        id: updateData.id,
        specs: updateData.specs
      }
      
      await updateCart(cartUpdateData)
      // 更新本地数据
      if (updateData.specs) {
        item.specs = updateData.specs
      }
    } catch (error) {
      console.error('规格更新失败:', error)
      throw error
    }
  }

  // 从购物车移除商品
  const removeFromCart = async (cartItemId) => {
    try {
      await removeCartItem(cartItemId)
      cartItems.value = cartItems.value.filter(item => item.id !== cartItemId)
    } catch (error) {
      throw error
    }
  }

  // 批量删除购物车商品
  const batchRemoveFromCart = async (productIds) => {
    try {
      await removeCartItems(productIds)
      ElMessage.success('商品已批量移除')
      await fetchCartItems()
    } catch (error) {
      ElMessage.error('批量移除商品失败')
    }
  }

  // 计算总价 (只计算选中的商品)
  const totalPrice = computed(() => {
    return cartItems.value.reduce((sum, item) => {
      return sum + (item.selected ? (item.productCurrentPrice || 0) * (item.quantity || 0) : 0)
    }, 0)
  })

  // 计算总原价 (只计算选中的商品)
  const totalOriginalPrice = computed(() => {
    return cartItems.value.reduce((sum, item) => {
      return sum + (item.selected ? (item.productPrice || item.productCurrentPrice || 0) * (item.quantity || 0) : 0)
    }, 0)
  })

  // 计算总节省金额
  const totalSaved = computed(() => {
    return totalOriginalPrice.value - totalPrice.value
  })

  // 计算选中商品数量
  const selectedCount = computed(() => {
    return cartItems.value.filter(item => item.selected).length
  })

  // 计算属性：是否全选
  const isAllSelected = computed({
    get: () => cartItems.value.length > 0 && cartItems.value.every(item => item.selected),
    set: (value) => {
      cartItems.value.forEach(item => {
        item.selected = value
      })
    }
  })

  // 获取选中的商品
  const getSelectedItems = () => {
    return cartItems.value.filter(item => item.selected)
  }

  // 清空购物车
  const clearCart = () => {
    cartItems.value = []
  }

  return {
    cartItems,
    loading,
    fetchCartItems,
    addToCart,
    removeFromCart,
    batchRemoveFromCart,
    updateQuantityToServer,
    updateCartItemSpecs,
    totalPrice,
    totalOriginalPrice,
    totalSaved,
    selectedCount,
    isAllSelected,
    getSelectedItems,
    clearCart
  }
}, {
  persist: true,
}) 